using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Text;
using System.Web;
using System.Web.Configuration;

using Comics.Providers;

namespace Comics.Services
{
	/// <summary>
	/// This class is the primary gateway between
	/// the business layer and the data provider 
	/// layer.
	/// </summary>
	public sealed class Service
	{

		private static DataProvider m_provider;
		private static DataProviderCollection m_providers;
		private static object m_lock = new object();

		/// <summary>
		/// Gets the current provider.
		/// </summary>
		public static DataProvider Provider
		{
			get { return m_provider; }
		}

		/// <summary>
		/// Gets a collection of all registered providers.
		/// </summary>
		public static DataProviderCollection Providers
		{
			get { return m_providers; }
		}

		/// <summary>
		/// Load the providers from the web.config.
		/// </summary>
		private static void LoadProviders()
		{
			// Avoid claiming lock if providers are already loaded
			if (m_provider == null)
			{
				lock (m_lock)
				{
					// Do this again to make sure m_provider is still null
					if (m_provider == null)
					{
						// Get a reference to the <DataProvider> section
						DataProviderSection _section = (DataProviderSection)WebConfigurationManager.GetSection("Comics/DataProvider");

						// Load registered providers and point _provider
						// to the default provider
						m_providers = new DataProviderCollection();
						ProvidersHelper.InstantiateProviders(_section.Providers, m_providers, typeof(DataProvider));
						m_provider = m_providers[_section.DefaultProvider];

						if (m_provider == null)
							throw new Exception("Unable to load default DataProvider");
					}
				}
			}
		}

        public static StringDictionary LoadSettings()
		{
			LoadProviders();
			return m_provider.LoadSettings();
		}

        public static void SaveSettings(StringDictionary settings)
		{
			LoadProviders();
			m_provider.SaveSettings(settings);
		}

	}
}